package cn.maiyar.common.serializer;

import cn.maiyar.common.annotation.JacksonBigDecimal;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Objects;

/**
 * BigDecimal序列化(默认保留二位小数和四舍五入)
 *
 * @author c.c
 */
@Getter
@Setter
@NoArgsConstructor
public class BigDecimalSerialize extends JsonSerializer<BigDecimal> implements ContextualSerializer {

    protected DecimalFormat decimalFormat;

    @Override
    public void serialize(BigDecimal bigDecimal, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (bigDecimal == null) {
            gen.writeNull();
        } else {
            if (decimalFormat == null) {
                gen.writeNumber(bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP));
            } else {
                gen.writeString(decimalFormat.format(bigDecimal));
            }
        }
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        if (property == null) {
            return prov.findNullValueSerializer(null);
        }
        // 判断类型是否是BigDecimal
        if (Objects.equals(property.getType().getRawClass(), BigDecimal.class)) {
            JacksonBigDecimal annotation = property.getAnnotation(JacksonBigDecimal.class);
            if (annotation != null) {
                String pattern = annotation.pattern();
                decimalFormat = new DecimalFormat(pattern);
                return this;
            }
        }
        return prov.findValueSerializer(property.getType(), property);
    }
}
